package com.jstyle.jclife.activity;

import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.model.NetResultData;

import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.SHA1;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.EditTextWithDelete;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.tv_register_title)
    TextView tvRegisterTitle;
    @BindView(R.id.tv_register_tips)
    TextView tvRegisterTips;
    @BindView(R.id.edit_register_name)
    EditTextWithDelete editRegisterName;
    @BindView(R.id.edit_register_email)
    EditTextWithDelete editRegisterEmail;
    @BindView(R.id.edit_register_pwd)
    EditTextWithDelete editRegisterPwd;
    @BindView(R.id.bt_register_next)
    Button btRegisterNext;
    @BindView(R.id.tv_register_tologin)
    TextView tvRegisterTologin;
    Disposable registerDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        tvRegisterTologin.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    }

    @OnClick({R.id.bt_register_next, R.id.tv_register_tologin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_register_next:
                toRegister();
                break;
            case R.id.tv_register_tologin:
                startActivity(LoginActivity.class);
                break;
        }
    }

    private void toRegister() {
        final String nickName = editRegisterName.getText().toString();
        final String email = editRegisterEmail.getText().toString();
        final String pwd = editRegisterPwd.getText().toString();
        if (TextUtils.isEmpty(nickName) || TextUtils.isEmpty(email) || TextUtils.isEmpty(pwd)) {
            showToast(getString(R.string.fill_all_info));
            return;
        }
        if (!NetWorkUtil.isNetworkConnected(this)) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        if (pwd.length() < 6) {
            showToast(getString(R.string.psd_too_short));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put(NetWorkConast.KEY_userEmail, email);
        map.put(NetWorkConast.KEY_NickName, nickName);
        map.put(NetWorkConast.KEY_userpwd, SHA1.md5Encoder(pwd));

        NetWorkUtil.addSHA1(map);
        NetWorkUtil.getInstance().getJstyleApi().register(map).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                registerDisposable = disposable;
                showProgressDialog(getString(R.string.Signing));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<NetResultData<Long>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData<Long> netResultData) {
                disMissProgressDialog();
                int msgCode = netResultData.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode, RegisterActivity.this);
                if (msgCode == NetResultData.Success_Code) {
                    long uid= netResultData.getData();
                    saveUserInfo(uid,nickName,email,pwd);
                    msg = getString(R.string.sign_up_complete);

                    finish();
                }
                showToast(msg);
            }

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void saveUserInfo(long uid,String nickName,String account,String pwd){
        UserInfo userInfo=new UserInfo();
        userInfo.setName(nickName);
        userInfo.setPhone(account);
        userInfo.setUserId(String.valueOf(uid));
        UserInfoDaoManager.insertUser(userInfo);
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, true);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, account);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, pwd);
        startActivity(String.valueOf(uid));
    }
    private void startActivity(String uid){
        boolean isFirst = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_Is_First, true);
        if(isFirst){
            startActivity(BindDeviceActivity.class);
        }else{
            List<BindDeviceInfo> bindDeviceInfoList= BindDeviceInfoDaoManager.queryAllData();
            Class next=null;
            if(bindDeviceInfoList.size()!=0){
                next=UserInfoSettingActivity.class;
            }else{
                next=BindDeviceActivity.class;
            }
            startActivity(next,SharedPreferenceUtils.KEY_From_Login,true);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(registerDisposable);
    }

    @Override
    protected void finishLoginIn() {
        super.finishLoginIn();
        finish();
    }
}
